package com.vnp.cooking;

import java.util.ArrayList;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.vnp.cooking.adapter.NhabepGridAvapter;
import com.vnp.cooking.adapter.NhabepListAdpater;
import com.vnp.cooking.bean.ObjCookpad;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.PreferenceHelper;
import com.vnp.cooking.utils.Utils;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class CongthucDadangActivity extends Activity implements OnClickListener, OnScrollListener{
	
	ListView listDadang;
	GridView gridDadang;
	ImageButton btnBack;
	NhabepListAdpater listAdapter;
	NhabepGridAvapter gridAdapter;
	ImageButton btnSortDisplay;
	
	// load more
	boolean isLoading = false;
	Button btnLoadmore;
	int mPage = 0;
	
	ArrayList<ObjCookpad> cookpads = new ArrayList<ObjCookpad>();
	
	// footer view
	View footerMain;
	Button btnLoadMore;
	ProgressBar progressBarLoadmore;
	PreferenceHelper preferenceHelper;
	ProgressBar progressBar;
	TextView noDadang;
	
	String idPerson;
	View actionbar;
	
	TextView title_dadang;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_congthuc_dadang);
		
		preferenceHelper = new PreferenceHelper(this);
		
//		preferenceHelper.setID("1118396");
		idPerson = getIntent().getStringExtra("userID");
		
		actionbar = (View) findViewById(R.id.actionbar);
		
		title_dadang = (TextView) findViewById(R.id.title_congthuc_dadang);
		
		noDadang = (TextView) findViewById(R.id.txt_no_dadang);
		listDadang = (ListView) findViewById(R.id.list_dadang);
		gridDadang = (GridView) findViewById(R.id.gridview);
		
		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnSortDisplay = (ImageButton) findViewById(R.id.btn_sort_display);
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		// add footer listview
		addFooterView();
		getMonAnDaDang(mPage);
		gridAdapter = new NhabepGridAvapter(this, cookpads);
		listAdapter = new NhabepListAdpater(this, cookpads);
		
		setFont();
		
		init();
		
	}
	
	private void setFont() {
		title_dadang.setTypeface(Utils.getTypefaceRegular(CongthucDadangActivity.this));
	}
	
	void init() {
		btnSortDisplay.setOnClickListener(this);
		btnBack.setOnClickListener(this);
		listDadang.setAdapter(listAdapter);
		listDadang.setOnScrollListener(this);
		actionbar.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		case R.id.actionbar:
			listDadang.smoothScrollToPosition(0);
			break;
		case R.id.btn_back:
			closeActivity();
			break;

		case R.id.btn_sort_display:
			changeListGrid();
			break;
		
		case R.id.btn_load_more:
			mPage = mPage + 1;
			getMonAnDaDang(mPage);
			progressBarLoadmore.setVisibility(View.VISIBLE);
			btnLoadMore.setText("Đang lấy thêm công thức...");
			break;
		}
	}
	
	
	// change list and grid
		public void changeListGrid() {
			if (gridDadang.getVisibility() == View.VISIBLE) {
				gridDadang.setVisibility(View.GONE);
				listDadang.setVisibility(View.VISIBLE);
				listDadang.setAdapter(listAdapter);
				btnSortDisplay.setImageResource(R.drawable.ic_grid_sort_03);
			} else {
				listDadang.setVisibility(View.GONE);
				gridDadang.setVisibility(View.VISIBLE);
				gridAdapter = new NhabepGridAvapter(this,
						cookpads);
				gridDadang.setAdapter(gridAdapter);
				btnSortDisplay.setImageResource(R.drawable.ic_list_sort_05);
			}
		}
	
	
	// data fix

		

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount != 0) {
//					new loadMoreListView().execute();
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}

		void addMoreItem() {
		}
		
		// load more listview
		private class loadMoreListView extends AsyncTask<Void, Void, Void> {

			@Override
			protected Void doInBackground(Void... unused) {
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						/*mPage += 1;
						
						// get listview current position - used to maintain scroll position
	                    int currentPosition = listDadang.getFirstVisiblePosition();
	                    listAdapter = new NhabepListAdpater(CongthucDadangActivity.this, cookpads);
	                    listDadang.setAdapter(listAdapter);
	                 // Setting new scroll position
	                    listDadang.setSelectionFromTop(currentPosition + 1, 0);*/
					}
				});
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
			}
		}
		
		
		// add footer view cong thuc da dang
		void addFooterView() {
			View loadMoreView = ((LayoutInflater) this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
					R.layout.footer_loadmore, null, false);
			footerMain = (View) loadMoreView.findViewById(R.id.footer_main);
			footerMain.setVisibility(View.GONE);
			listDadang.addFooterView(loadMoreView);
			btnLoadMore = (Button) loadMoreView.findViewById(R.id.btn_load_more);
			progressBarLoadmore = (ProgressBar) loadMoreView.findViewById(R.id.progressBar1);
			btnLoadMore.setOnClickListener(this);
		}
		
		// get data mon an da dang
		public void getMonAnDaDang(int page) {
			HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

				@Override
				public void onFailure(Throwable error) {
					hiddenProgessDialog();
					btnLoadMore.setText("Lấy thêm công thức");
					progressBarLoadmore.setVisibility(View.GONE);
					super.onFailure(error);
				}

				@Override
				public void onSuccess(JSONObject re) {
					hiddenProgessDialog();
					try {
						int status = re.getInt("status");
						if (status == 200) {
							btnLoadMore.setText("Lấy thêm công thức");
							progressBarLoadmore.setVisibility(View.GONE);
							JSONArray jo = re.getJSONArray("data");
							if (jo.length() == 0) {
								footerMain.setVisibility(View.GONE);
								progressBarLoadmore.setVisibility(View.GONE);
								noDadang.setVisibility(View.VISIBLE);
								return;
							}
							if (jo.length() < 11) {
								footerMain.setVisibility(View.GONE);
								progressBarLoadmore.setVisibility(View.GONE);
							}
							Log.i("DATA","DATA nhan ve : " + jo.toString());
							for (int i = 0; i < jo.length(); i++) {
								JSONObject joCookpad = jo.getJSONObject(i);
								ObjCookpad objCookpad = new ObjCookpad();
								objCookpad.setId(joCookpad.getString("id"));
								objCookpad.setNameCookpad(joCookpad.getString("name"));
								objCookpad.setDescriptionCookpad(joCookpad.getString("desc"));
								objCookpad.setViewedCookpad(joCookpad.getInt("view_count"));
								objCookpad.setLikeCookpad(joCookpad.getInt("like_count"));
								// getImage
								JSONObject image = joCookpad.getJSONObject("image");
								objCookpad.setUrlImageCookpad(image.getString("cover"));
								
								objCookpad.setThoigianNauan(joCookpad.getString("time"));
								
								
								/*JSONObject tacgia = joCookpad
										.getJSONObject("author");
								
								if (tacgia.isNull("author") == true) {
									objCookpad
											.setNamePersonCookpad("Vô danh");
									objCookpad.setIdNamePerson("");
								} else {
									objCookpad.setNamePersonCookpad(tacgia
											.getString("name"));
									objCookpad.setIdNamePerson(tacgia.getString("id"));
								}
								*/
								
								cookpads.add(objCookpad);
							}
							listAdapter.notifyDataSetChanged();
							footerMain.setVisibility(View.VISIBLE);
							
						} else {
							hiddenProgessDialog();
							btnLoadMore.setText("Lấy thêm công thức");
							progressBarLoadmore.setVisibility(View.GONE);
						}
						
					} catch (JSONException e) {
						hiddenProgessDialog();
						btnLoadMore.setText("Lấy thêm công thức");
						progressBarLoadmore.setVisibility(View.GONE);
						e.printStackTrace();
					}
				}
				
			});
			
			httpClientHelper.getCongThucDaDang(idPerson, page);
		}
		
		// hide progress bar
		void hiddenProgessDialog() {
			try {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						try {
							progressBar.setVisibility(View.GONE);
						} catch (Exception e) {
						}
					}
				});
			} catch (Exception e) {
			}
	
		}
		
		void closeActivity(){
			finish();
			overridePendingTransition(R.anim.open_main, R.anim.close_next);
		}


		@Override
		public void onBackPressed() {
			closeActivity();
		}
}


